﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CommonClassLibrary
{
    internal class TaskHelp
    {
        /// <summary>
        /// 控制Task数量 设置
        /// </summary>
        static void TestMethod()
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;
            ManualResetEvent resetEvent = new ManualResetEvent(true);

            List<Task> tasks = new List<Task>();
            for (int i = 0; i < 30; i++)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("任务取消");
                    return;
                }
                var task = Task.Factory.StartNew((index) =>
                {
                    Console.WriteLine(index);
                    Thread.Sleep(3000);
                }, i, token);
                tasks.Add(task);
                if (tasks.Count > 5)
                {
                    Console.WriteLine("线程等待任一完成");
                    Task.WaitAny(tasks.ToArray());
                    Console.WriteLine("完成线程x");
                    tasks = tasks.Where(d => d.Status != TaskStatus.RanToCompletion).ToList();

                    if (i > 10)
                    {
                        tokenSource.Cancel();
                        Console.WriteLine("开始任务取消");
                    }
                }
            }
            Console.WriteLine("任务结束");
        }
    }
}
